import time
import traceback

import uiautomator2 as u2


def share(url):
    try:
        # d = u2.connect()

        # 手机内连接
        d = u2.connect('0.0.0.0')
        d.implicitly_wait(120.0)  # 设置元素查找等待时间
        d.unlock()
        time.sleep(1)
        print(d.app_current())

        down_img(d, url)

        d.app_stop('org.telegram.messenger')
        time.sleep(2)
        d.app_start('org.telegram.messenger', use_monkey=True)
        time.sleep(6)
        # d.click(0.937, 0.064)
        d(description="Search").click()
        time.sleep(2)
        d.send_keys("JustJoking", clear=True)
        time.sleep(2)
        d(textContains='JustJoking', className='android.view.ViewGroup').click()
        time.sleep(2)
        # 打开附件
        d.click(0.817, 0.873)
        # d.long_click(0.44, 0.873)
        # time.sleep(2)
        # d(text="粘贴").click()
        time.sleep(2)
        # 选中第一张
        d.click(0.614, 0.436)
        time.sleep(2)
        # 发送
        d.click(0.896, 0.848)
        time.sleep(2)
        # d(description="Send").click()
        # time.sleep(2)
        d.send_keys(url, clear=True)
        time.sleep(2)
        d.click(0.929, 0.847)
        time.sleep(2)
        d.app_start("com.termux")
        time.sleep(1)
    except:
        print(traceback.format_exc())
        pass


def down_img(d, url):
    d.app_start('com.android.chrome', 'com.google.android.apps.chrome.Main', use_monkey=True,
                stop=True, wait=True)
    time.sleep(10)
    url_bar = d(resourceId="com.android.chrome:id/url_bar")
    if url_bar:
        url_bar.click()
    else:
        searchBtn = d.xpath('//*[@resource-id="com.android.chrome:id/search_box"]/android.widget.RelativeLayout[1]')
        searchBtn.click()
    time.sleep(2)
    d.send_keys(url, clear=True)
    time.sleep(2)
    d.press('enter')
    time.sleep(10)
    d(scrollable=True).scroll.toEnd()
    time.sleep(3)
    d(scrollable=True).scroll.vert.to(text="")
    time.sleep(10)
    share = d(text="")
    print("share.exists",share.exists)
    share.click()
    time.sleep(2)
    # d(resourceId="pv_id_1_4").click()
    d(text="Image", className='android.view.MenuItem').click()
    # d.xpath('//*[@text="Just joking"]/android.view.View[1]/android.view.View[1]/android.view.View[3]/android.view.View[5]/android.view.View[1]/android.view.View[1]/android.view.View[1]/android.view.MenuItem[5]').click()
    time.sleep(10)
    d(text="Download").click()
    # d.long_click(0.407, 0.305)
    # time.sleep(5)
    # d(resourceId="com.android.chrome:id/menu_row_text", text="复制图片").click()
    time.sleep(2)


if __name__ == '__main__':
    share("https://justjoking.ai/detail/1436")
